package com.dataSructure.list.linked.singlinked;

public class LinkedDemo {


    public static void main(String[] args) {

        LinkedList linkedList = new LinkedList();

        LinkedNode hero1 = new LinkedNode(1, "宋江");
        LinkedNode hero2 = new LinkedNode(2, "卢俊义");
        LinkedNode hero3 = new LinkedNode(3, "吴用");
        LinkedNode hero4 = new LinkedNode(4, "林冲");
        LinkedNode hero5 = new LinkedNode(5, "林");

        linkedList.add(hero1);
        linkedList.add(hero2);
        linkedList.add(hero3);
        linkedList.add(hero4);
        linkedList.addOrder(hero5);

        linkedList.list();

    }

    public int getLength(LinkedNode head) {
        if (head.next == null) return 0;

        int length = 0;
        LinkedNode cur = head.next;
        while (cur != null) {
            length++;
            cur = cur.next;
        }
        return length;

    }

    public LinkedNode findLastIndexNode(LinkedNode head, int index){

        if(head.next == null) return null;

        int length = this.getLength(head);

        if(index <= 0 || index >length) return  null;

        LinkedNode cur = head.next; //next node
        while (cur.next != null ){

            if (cur.next.no == length - index){
                return cur;
            }
            cur = cur.next;   // next
        }
        return cur;
    }

    public void reversetList(LinkedNode head){
        if(head.next == null) return;

        LinkedNode cur = head.next;
        LinkedNode next = null;// 指向当前节点[cur]的下一个节点
        LinkedNode reverseHead = new LinkedNode(0,"");
        while (cur != null){
            next = cur.next;
            cur.next = reverseHead.next;//将cur的下一个节点指向新的链表的最前端
            reverseHead.next = cur; //将cur 连接到新的链表上
            cur = next;//让cur后移
        }
        //将head.next 指向 reverseHead.next , 实现单链表的反转
        head.next = reverseHead.next;

    }
}
